// txtReaderView.cpp : implementation of the CTxtReaderView class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "resource.h"
#include "txtReaderView.h"

BOOL CTxtReaderView::PreTranslateMessage(MSG* pMsg)
{
	pMsg;
	return FALSE;
}

LRESULT CTxtReaderView::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	wchar_t *pBuf = NULL;
	int nPageSize = 0;
	m_loader.GetCurPage(&pBuf, nPageSize);
	if (pBuf != NULL && nPageSize > 0)
	{
		CRect rcClient;
		GetClientRect(&rcClient);
		
		CPaintDC dc(m_hWnd);
		CMemoryDC memDC(dc.m_hDC, rcClient);
		
		memDC.FillSolidRect(&rcClient, RGB(192, 220, 192));
		memDC.SetBkMode(TRANSPARENT);
		
		rcClient.DeflateRect(20, 20, 20, 40);

		DRAWTEXTPARAMS par;
		memset(&par, 0, sizeof(par));
		par.cbSize = sizeof(par);
		par.iTabLength = 4;
		par.iLeftMargin = 10;
		par.iRightMargin = 10;

		int nheight = 0;
		int rcHeight = rcClient.Height();
		int nStep = 100;
		bool bForward = true;
		while (1)
		{
			nheight = memDC.DrawText(pBuf, nPageSize, &rcClient, DT_CALCRECT|DT_NOCLIP|DT_EXPANDTABS|DT_TABSTOP|DT_WORDBREAK|DT_LEFT);
			if (abs(nheight - rcHeight) <= 2 || nStep <= 1)
			{
				break;
			}

			if (bForward && nheight < rcHeight)
			{
				nStep;// /= 2;
			}
			else if (bForward && nheight > rcHeight)
			{
				nStep = -nStep/2;
			}
			else if (!bForward && nheight < rcHeight)
			{
				nStep = -nStep/2;
			}
			else if (!bForward && nheight > rcHeight)
			{
				nStep; //= 2;
			}

			m_loader.ResizePage(nPageSize, nStep);
		}

		memDC.FillSolidRect(&rcClient, RGB(192, 220, 192));
		memDC.DrawTextEx(pBuf, nPageSize, &rcClient, DT_NOCLIP|DT_EXPANDTABS|DT_TABSTOP|DT_WORDBREAK|DT_LEFT, &par);
	}

	return 0;
}

LRESULT CTxtReaderView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	TCHAR szExe[MAX_PATH] = {0};
	GetModuleFileName(NULL, szExe, MAX_PATH);
	CString strExe(szExe);
	strExe = strExe.Left(strExe.ReverseFind(_T('\\')));
	strExe = strExe.Left(strExe.ReverseFind(_T('\\')));
	strExe.Append(_T("\\testdata\\test.txt"));

	if (!m_loader.LoadFile(strExe.GetBuffer()))
	{
		return 0;
	}

	return 0;
}

LRESULT CTxtReaderView::OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	return 0;
}

LRESULT CTxtReaderView::OnKeyDown( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	BOOL bPaint = TRUE;
	switch (wParam)
	{
	case VK_NEXT:
		m_loader.NextPage();
		break;
	case VK_PRIOR:
		m_loader.PrePage();
		break;
	default:
		bPaint = FALSE;
		break;
	}

	if (bPaint)
	{
		InvalidateRect(NULL);
	}

	return 0;
}